#pragma once

#include "Comm.hpp"

#include <iostream>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <cstdio>
#include <string>
#include <unistd.h>

const int g_defaultId = -1;
const int g_size = 4096;
int g_mode = 0666;

#define PATHNAME "."
#define PROJID 0x67
#define CREATOR "creator"
#define USER "user"

class Shm
{
private:
    // 辅助函数
    void CreateAssist(int flg)
    {
        _shmid = shmget(_key, _size, flg);
        if (_shmid < 0)
            ERR_EXIT("shmget");
        printf("%d\n", _shmid);
    }
    // 创建共享内存
    void Create()
    {
        CreateAssist(IPC_CREAT | IPC_EXCL | g_mode);
    }
    // 获取共享内存
    void Get()
    {
        CreateAssist(IPC_CREAT);
    }
    // 映射共享内存
    void Attach()
    {
        _shmaddr = shmat(_shmid, nullptr, 0);
        if ((long)_shmaddr < 0)
            ERR_EXIT("shmat");
        printf("attach success!\n");
    }
    // 去关联
    void Detach()
    {
        int n = shmdt(_shmaddr);
        if (n < 0)
            ERR_EXIT("shmdt");
        printf("detach success!\n");
    }
    // 释放共享内存
    void Destroy()
    {
        Detach();
        if (_userType == CREATOR)
        {
            int n = shmctl(_shmid, IPC_RMID, nullptr);
            if (n >= 0)
            {
                printf("shmctl removes %d success!\n", _shmid);
            }
            else
                ERR_EXIT("shmctl");
        }
    }

public:
    Shm(const std::string &pathname, int projid, const std::string &userType)
        : _shmid(g_defaultId), _size(g_size), _shmaddr(nullptr), _userType(userType)
    {
        _key = ftok(pathname.c_str(), projid);
        if (_key < 0)
            ERR_EXIT("ftok");
        printf("key: 0x%x\n", _key);
        if (_userType == CREATOR)
            Create();
        else if (_userType == USER)
            Get();
        else
        {
            //...
        }
        Attach();
    }
    // 得到共享内存虚拟地址
    void *VirtualAddr()
    {
        printf("_shaddr: %p\n", _shmaddr);
        return _shmaddr;
    }
    // 获取共享内存属性
    void Attr()
    {
        struct shmid_ds ds; // 输出型参数
        int n = shmctl(_shmid, IPC_STAT, &ds);
        if (n < 0)
            ERR_EXIT("shmctl");
        printf("segsz: %d\n", ds.shm_segsz);
        printf("key: %d\n", ds.shm_perm.__key);
    }

    ~Shm()
    {
        Destroy();
    }

private:
    int _shmid;
    int _key;
    int _size;
    void *_shmaddr;
    std::string _userType;
};